<template>
    <div class="intelligentTraining knowledge-container">
        <div class="treeContent" v-show="!editShow">
            <div class="header">
                <span>问题分类</span>
            </div>
            <knowledgeTree @getClassId="getClassId" :optionList.sync="optionList" type="class" :canEdit="false">
            </knowledgeTree>
        </div>
        <div class="container calcwidth" v-show="!editShow">
            <p class="tips">收集所有机器人学到的标准问题可能对应的相似问法，通过学习可以进一步完善知识库。</p>
            <div class="header flexbetween mb20">
                <el-input placeholder="请输入关键字搜索" v-model="searchInput" @keyup.enter.native="getItTrainingList" size="small"
                          style="width: 200px">
                    <span slot="suffix" class="iconfont icon-sousuo" @click="getItTrainingList"></span>
                </el-input>
            </div>
            <element-table :data="itTrainingList" :columns="cloumns" :loading="tableLoading" :tableHeight="tableHeight" :pageNo="pageNo"
                           :pageSize="pageSize" :total="total" @changePageNo="changePageNo" @changePageSize="changePageSize">
            </element-table>
        </div>

        <div class="editContaner" v-show="editShow">
            <div class="header flexbetween mb20">
                <span>智能训练</span>
                <el-button size="small" plain @click="returnList">返回列表</el-button>
            </div>
            <div class="trainConfig">
                <div class="configFrom">
                    <p class="mb20" style="color: #363C43;font-weight: bold;">标准问题</p>
                    <el-form :model="trainingForm" ref="trainingForm" label-width="75px">
                        <el-form-item label="问题" prop="question">
                            <el-input size="small" :disabled="true" v-model="trainingForm.question" />
                        </el-form-item>
                        <el-form-item label="答案" prop="answer">
                            <el-input type="textarea" :rows="5" :disabled="true" placeholder="请输入内容" v-model="trainingForm.answer">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="分类" prop="className" style="margin-bottom: 10px">
                            <span>{{trainingForm.className}}</span>
                        </el-form-item>
                    </el-form>
                    <p class="mb20" style="color: #363C43;font-weight: bold;">可能问法列表<span
                              class="sub-title">请务必认真审核符合条件的问题，如果符合可以直接通过，不符合可以选择回答，在里面选择或者编辑其他的答案回复</span></p>
                    <p class="mb20">
                        <el-button size="small" plain @click="batchPass">批量通过</el-button>
                        <el-button size="small" plain @click="batchIgnore">批量忽略</el-button>
                    </p>
                    <div class="elementTable">
                        <el-table :data="innerTrainList" v-loading="innerLoading" border fit :height="500"
                                  @selection-change="checkboxSelect" row-key="messageHistoryId">
                            <el-table-column type="selection" width="45"></el-table-column>
                            <el-table-column prop="question" label="问题"></el-table-column>
                            <el-table-column prop="createTime" label="时间"></el-table-column>
                            <el-table-column label="操作" width="250">
                                <template slot-scope="scope">
                                    <div class="operation">
                                        <el-tooltip effect="light" content="通过" placement="top" :enterable="false"
                                                    v-if="menuAuthCodes.includes('M75')">
                                            <span class="iconfont icon-tongguo"
                                                  @click="pass(scope.row.question, scope.row.messageHistoryId)"></span>
                                        </el-tooltip>
                                        <el-tooltip effect="light" content="编辑通过" placement="top" :enterable="false"
                                                    v-if="menuAuthCodes.includes('M75')">
                                            <span class="iconfont icon-bianjitongguo"
                                                  @click="passByEdit(scope.row.question, scope.row.messageHistoryId)"></span>
                                        </el-tooltip>
                                        <el-tooltip effect="light" content="忽略" placement="top" :enterable="false"
                                                    v-if="menuAuthCodes.includes('M76')">
                                            <span class="iconfont icon-hulve" @click="ignore(scope.row.messageHistoryId)"></span>
                                        </el-tooltip>
                                        <el-tooltip effect="light" content="回答" placement="top" :enterable="false"
                                                    v-if="menuAuthCodes.includes('M77')">
                                            <span class="iconfont icon-huida1"
                                                  @click="answerDetail(scope.row.question, scope.row.messageHistoryId)"></span>
                                        </el-tooltip>
                                        <el-tooltip effect="light" content="查看聊天记录" placement="top" :enterable="false">
                                            <span class="iconfont icon-chakanliaotianjilu1" @click="openChatList(scope)"></span>
                                        </el-tooltip>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination @size-change="innerChangePageSize" @current-change="innerChangePageNo" :current-page="innerPageNo"
                                       :page-sizes="[5, 10, 15, 20, 30, 50 ,100]" :page-size="innerPageSize"
                                       layout="->, sizes, total, prev, pager, next" :total="innerTotal" background>
                        </el-pagination>
                    </div>
                </div>
                <div class="buttomBtn">
                    <el-button size="small" type="primary" @click="prev">上一条</el-button>
                    <el-button size="small" type="primary" @click="next">下一条</el-button>
                </div>
            </div>
        </div>

        <!-- 回答问题 -->
        <reply-question :replyVisible.sync="replyVisible" :answeringQuestion="answeringQuestion" @getSelectedAnswer="selectedAnswerVal"
                        @finishAnswer="finishAnswer"></reply-question>

        <el-dialog :visible.sync="chatVisible" title="查看聊天记录" width="980px" custom-class="chatListDialog" :before-close="beforeCloseChat">
            <el-tabs v-model="activeName" @tab-click="getChatList">
                <el-tab-pane label="本次" name="nearby"></el-tab-pane>
                <el-tab-pane label="全部" name="allList"></el-tab-pane>
            </el-tabs>
            <chat-list :chatListData="chatListData" ref="chatList"></chat-list>
        </el-dialog>

        <el-dialog title="编辑问题" :visible="editQsVisible" width="640px" :before-close="beforeCloseEditQs" class="setDialog">
            <el-form label-width="100px" :model="editQsForm" :rules="editQsRules" ref="editQsForm">
                <el-form-item label="问题:" prop="editQuestion">
                    <el-input v-model="editQsForm.editQuestion" size="small" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="beforeCloseEditQs" size="small" type="text">取 消</el-button>
                <el-button type="primary" size="small" @click="submitEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import knowledgeTree from "@/components/knowledgeTree";
import elementTable from "@/components/elementTable";
import chatList from "@/components/chatList/index.vue";
import replyQuestion from "@/components/replyQuestion";
import { getChatListCommon } from "@/api/chatList.js";
import {
    itTrainingListMethod,
    getIntelligentTrain,
    detailTrainingList,
    batchPassMethod,
    batchIgnoreMethod,
    answerDetailQuestion
} from "@/api/intelligentTraining.js";
export default {
    name: "intelligentTraining",
    data() {
        return {
            treeId: "0",
            data: [{
                id: "0",
                label: "全部分类",
                children: [],
            },],
            classList: [],
            optionList: [],
            searchInput: "",
            labelType: "add",
            labelVisible: false,
            labelClassId: null,
            labelEditId: "",
            labelName: "",
            itTrainingList: [],
            innerTrainList: [],
            tableLoading: false,
            innerLoading: false,
            pageNo: 1,
            innerPageNo: 1,
            pageSize: 10,
            innerPageSize: 10,
            total: 0,
            innerTotal: 0,
            editShow: false,
            cloumns: [{
                config: {
                    label: "问题",
                },
                render: (h, scope) => {
                    return (<el-link type="primary" underline={false} onClick={() => this.jumpToDetail(scope.id)}>{scope.question}</el-link>);
                },
            }, {
                config: {
                    label: "待学习个数",
                    prop: "likelyQuestionCount"
                },
            }, {
                config: {
                    label: "时间",
                    prop: "createTime"
                },
            }],
            trainingForm: {
                question: "",
                answer: "",
                className: ""
            },
            selectedList: [],
            innerId: "",
            chatVisible: false,
            chatListParam: {},
            answeringQuestion: "",
            answeringMid: "",
            answeringId: "",
            replyVisible: false,
            editQsVisible: false,
            editQsForm: {
                editQuestion: "",
                messageHistoryId: "",
            },
            editQsRules: {
                editQuestion: [{
                    required: true,
                    message: '问题不能为空',
                    trigger: "change"
                }]
            },
            activeName: "nearby",
            chatListData: [],
            currentIndex: 0
        }
    },
    created() {
        this.getItTrainingList();
    },
    methods: {
        getClassId(classId) {
            this.treeId = classId;
            this.pageNo = 1;
            this.getItTrainingList();
        },
        //列表
        getItTrainingList() {
            if (!this.menuAuthCodes.includes("M74")) {
                return;
            }
            this.tableLoading = true;
            var param = {
                classId: this.treeId != "0" ? this.treeId : "",
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                keyword: this.searchInput
            }
            itTrainingListMethod(param).then(resp => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.total = data.total;
                    this.itTrainingList = data.list;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        getInnerTrainList() {
            this.innerLoading = true;
            // 获取详情页的列表
            let param = {
                id: this.innerId,
                pageNo: this.innerPageNo,
                pageSize: this.innerPageSize
            };
            detailTrainingList(param).then(resp => {
                this.innerLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.innerTotal = data.total;
                    this.innerTrainList = data.list;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        jumpToDetail(cid) {
            // 跳转到详情页
            this.currentIndex = this.itTrainingList.findIndex(item => item.id == cid);
            this.innerId = cid;
            this.editShow = true;
            let param = { id: cid };
            getIntelligentTrain(param).then(resp => {
                // 获取详情页的表单字段
                if (resp.status == 0) {
                    this.trainingForm.question = resp.data.question;
                    this.trainingForm.answer = resp.data.answer;
                    this.trainingForm.className = resp.data.className;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
            this.getInnerTrainList();
        },
        pass(qs, mid) {
            this.$confirm("请确认是否通过?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                let param = [{
                    id: this.innerId,
                    question: qs,
                    messageHistoryId: mid
                }];
                batchPassMethod({ objList: param }).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("通过成功");
                        if (this.innerTotal == 1) {
                            this.returnList();
                            this.getItTrainingList();
                        } else {
                            this.getInnerTrainList();
                        }
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch();
        },
        passByEdit(qs, mid) {
            // 打开编辑通过的弹窗
            this.editQsForm.editQuestion = qs;
            this.editQsForm.messageHistoryId = mid;
            this.editQsVisible = true;
        },
        submitEdit() {
            // 提交编辑通过
            let param = [{
                id: this.innerId,
                question: this.editQsForm.editQuestion,
                messageHistoryId: this.editQsForm.messageHistoryId
            }];
            batchPassMethod({ objList: param }).then(resp => {
                if (resp.status == 0) {
                    this.$antMessage.success("编辑通过成功");
                    this.beforeCloseEditQs();
                    if (this.innerTotal == 1) {
                        this.returnList();
                        this.getItTrainingList();
                    } else {
                        this.getInnerTrainList();
                    }
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        ignore(mid) {
            this.$confirm("请确认是否忽略?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                let param = {};
                let objArr = [];
                objArr.push({
                    id: this.innerId,
                    messageHistoryId: mid
                });
                param.objList = objArr;
                batchIgnoreMethod(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("忽略成功");
                        if (this.innerTotal == 1) {
                            this.returnList();
                            this.getItTrainingList();
                        } else {
                            this.getInnerTrainList();
                        }
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch();
        },
        answerDetail(qs, mid) {
            // 打开回答的弹窗
            this.answeringQuestion = qs;
            this.answeringMid = mid;
            this.answeringId = this.innerId;
            this.replyVisible = true;
        },
        openChatList(obj) {
            // 查看聊天记录
            this.chatListParam = {
                messageHistoryId: obj.row.messageHistoryId,
                sourceId: obj.row.sourceId,
                clientId: obj.row.clientId
            };
            this.chatListData = [];
            this.getChatList();
            this.chatVisible = true;
        },
        getChatList() {
            let listUrl = "/v1/admin/message/getMessageHistoryById";
            let param = {
                messageHistoryId: this.chatListParam.messageHistoryId,
                sourceId: this.chatListParam.sourceId,
                clientId: this.chatListParam.clientId,
            };
            if (this.activeName == "allList") {
                listUrl = "/v1/admin/message/getMessageHistoryList";
                delete param.messageHistoryId;
            }
            getChatListCommon(param, listUrl).then(resp => {
                if (resp.status == 0) {
                    this.chatListData = resp.data;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        selectedAnswerVal(val) {
            // 选中某个问题答案进行回答
            let param = {
                id: this.answeringId,
                question: this.answeringQuestion,
                questionId: val,
                messageHistoryId: this.answeringMid
            }
            answerDetailQuestion(param).then(resp => {
                if (resp.status == 0) {
                    this.$antMessage.success("回答成功");
                    this.replyVisible = false;
                    if (this.innerTotal == 1) {
                        this.returnList();
                        this.getItTrainingList();
                    } else {
                        this.getInnerTrainList();
                    }
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        finishAnswer() {
            // 回答问题--编辑答案成功后
            let param = {
                objList: [{
                    id: this.answeringId,
                    messageHistoryId: this.answeringMid
                }],
            };
            batchIgnoreMethod(param).then(resp => {
                if (resp.status == 0) {
                    this.answeringQuestion = "";
                    this.answeringMid = "";
                    this.answeringId = "";
                    if (this.innerTotal == 1) {
                        this.returnList();
                        this.getItTrainingList();
                    } else {
                        this.getInnerTrainList();
                    }
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
            this.replyVisible = false;
        },
        beforeCloseChat() {
            this.activeName = "nearby";
            this.chatVisible = false;
        },
        returnList() {
            this.editShow = false;
        },
        checkboxSelect(arr) {
            this.selectedList = arr;
        },
        batchPass() {
            if (this.selectedList.length > 0) {
                this.$confirm("请确认是否批量通过?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    let param = [];
                    this.selectedList.forEach((item, index) => {
                        param.push({
                            id: this.innerId,
                            question: item.question,
                            messageHistoryId: item.messageHistoryId
                        });
                    });
                    batchPassMethod({ objList: param }).then(resp => {
                        if (resp.status == 0) {
                            this.$antMessage.success("批量通过成功");
                            if (this.innerTotal == 1) {
                                this.returnList();
                                this.getItTrainingList();
                            } else {
                                this.getInnerTrainList();
                            }
                        } else {
                            this.$antMessage.warning(resp.message);
                        }
                    });
                }).catch();
            } else {
                this.$antMessage.warning("请至少选择一条问题");
            }
        },
        batchIgnore() {
            if (this.selectedList.length > 0) {
                this.$confirm("请确认是否批量忽略?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    let param = {};
                    let objArr = [];
                    this.selectedList.forEach((item, index) => {
                        objArr.push({
                            id: this.innerId,
                            messageHistoryId: item.messageHistoryId
                        });
                    });
                    param.objList = objArr;
                    batchIgnoreMethod(param).then(resp => {
                        if (resp.status == 0) {
                            this.$antMessage.success("批量忽略成功");
                            if (this.innerTotal == 1) {
                                this.returnList();
                                this.getItTrainingList();
                            } else {
                                this.getInnerTrainList();
                            }
                        } else {
                            this.$antMessage.warning(resp.message);
                        }
                    });
                }).catch();
            } else {
                this.$antMessage.warning("请至少选择一条问题");
            }
        },
        beforeCloseEditQs() {
            this.editQsForm = {
                editQuestion: "",
                messageHistoryId: ""
            };
            this.$refs.editQsForm.resetFields();

            this.editQsVisible = false;
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getItTrainingList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getItTrainingList();
        },
        innerChangePageSize(val) {
            this.innerPageSize = val;
            this.getInnerTrainList();
        },
        innerChangePageNo(val) {
            this.innerPageNo = val;
            this.getInnerTrainList();
        },
        //上一个
        prev() {
            if (this.currentIndex > 0) {
                this.currentIndex -= 1;
                this.jumpToDetail(this.itTrainingList[this.currentIndex].id);
                return;
            }
            if (this.pageNo > 1) {
                this.pageNo -= 1;
                this.getItTrainingList((list) => {
                    this.currentIndex = list.length - 1;
                    this.jumpToDetail(list[this.currentIndex].id);
                });
            } else if (this.pageNo == 1) {
                this.$antMessage.warning("已经是第一个了");
            }
        },
        //下一个
        next() {
            var maxPageNo = Math.ceil(this.total / this.pageSize);
            if (this.currentIndex < this.itTrainingList.length - 1) {
                this.currentIndex += 1;
                this.jumpToDetail(this.itTrainingList[this.currentIndex].id);
                return;
            }
            if (this.pageNo < maxPageNo) {
                this.pageNo += 1;
                this.getItTrainingList((list) => {
                    this.currentIndex = 0;
                    this.jumpToDetail(list[this.currentIndex].id);
                });
            } else if (this.pageNo == maxPageNo) {
                this.$antMessage.warning("已经是最后一个了");
            }
        }
    },
    computed: {
        tableHeight() {
            return document.body.clientHeight - 280;
        },
        innerTableHeight() {
            return document.body.clientHeight - 300;
        },
    },
    components: {
        knowledgeTree,
        elementTable,
        chatList,
        replyQuestion
    }
}
</script>

<style lang="scss">
.intelligentTraining {
    overflow: initial;
    .tips {
        color: #90979d;
        margin-bottom: 20px;
    }
    .clickSpan {
        cursor: pointer;
    }
    .clickSpan:hover {
        text-decoration: underline;
    }
    .editContaner {
        width: 100%;
        padding-bottom: 50px;
        .header {
            > span {
                color: #363c43;
                font-size: 16px;
                padding-left: 8px;
                border-left: 2px solid #6b5ee2;
            }
        }
        .trainConfig {
            padding-left: 12px;
            padding-bottom: 20px;
            display: flex;
            position: relative;
            .el-form-item {
                .el-input__inner,
                .el-textarea__inner {
                    width: 50%;
                }
            }
            .el-table--border {
                .el-table__header {
                    width: 100% !important;
                }
            }
            .sub-title {
                color: #90979d;
                margin-left: 10px;
                font-weight: normal;
            }
            .buttomBtn {
                display: flex;
                align-items: center;
                height: 60px;
                position: absolute;
                bottom: 10px;
                left: 0px;
                .el-button {
                    margin-left: 20px;
                }
            }
        }
    }
    .chatListDialog {
        height: 680px;
        .el-dialog__body {
            padding-right: 0;
        }
        .robotChatLog {
            height: calc(100% - 65px);
            overflow-y: scroll;
        }
    }
}
</style>
